package com.java01.lang.net;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class HttpPost {

	public static void main(String args[]) {
		String outgoingString = null;
		try {
			outgoingString = URLEncoder.encode("Outgoing string to servlet", "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		try {
			URL url = new URL("http://webserver/servlet");
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setAllowUserInteraction(false);

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

			dos.writeBytes(outgoingString);
			dos.close();

			InputStream is = conn.getInputStream();
			int length;
			while ((length = is.read()) != -1) {
				System.out.write(length);
			}
			is.close();

			BufferedReader r = new BufferedReader(new InputStreamReader(is));
			StringBuffer buffer = new StringBuffer();
			String line;
			while ((line = r.readLine()) != null) {
				buffer.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
